package com.yuxinmuyu.sports_management.exception;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.validation.UnexpectedTypeException;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常处理
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public R businessExceptionHandler(BusinessException e) {
        logger.error(String.format("业务异常，详情：%s", e.getMsg()), e);
        return R.fail(e.getMsg());
    }


    /**
     * 参数类型错误
     */
    @ResponseBody
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R invalidFormatExceptionHandler(HttpMessageNotReadableException e) {
        logger.error(e.getMessage(),e);
        return R.fail("参数类型异常");
    }

    /**
     * 参数校验异常处理
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R exceptionHandler(MethodArgumentNotValidException e) {
        String errorMsgs = e.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        logger.error("请求参数校验错误，原因为：{}", errorMsgs);
        return R.fail(errorMsgs);
    }

    /**
     * 上传文件过大异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public R maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        logger.error("文件上传过大");
        return R.fail("上传文件过大");
    }

    /**
     * 不支持的文件格式异常处理
     */
    @ResponseBody
    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    public R httpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        logger.error("不支持的媒体格式{}，当前支持{}", e.getContentType(), e.getSupportedMediaTypes());
        return R.fail("不支持的媒体格式");
    }

    /**
     * 其他异常处理
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        e.printStackTrace();
        return R.fail(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
    }

    @ExceptionHandler(UnexpectedTypeException.class)
    public R UnexpectedTypeException(Exception e){
        e.printStackTrace();
        return R.fail(StringUtils.hasLength(e.getMessage())? e.getMessage() : "操作失败");
    }

}
